<template>
  <div class="login-container" :style="false === browserNotSupport ? 'background-image:url(' + bgImg + ')' : ''">
    <div v-if="true === browserNotSupport">
      <div class="browser-not-support-remind">
        <div>非常抱歉，本系统不支持当前浏览器！</div>
        <div>请下载谷歌浏览器，或切换至极速模式！</div>
      </div>
      <div class="browser-not-support-download">
        <a href="https://pc.qq.com/detail/1/detail_2661.html" target="_blank">下载谷歌浏览器</a>
      </div>
    </div>
    <div v-if="false === browserNotSupport">
      <el-container style="height: 840px;width: 100%;">
        <el-header class="c-login-header">
          <el-row class="c-lt">
            <el-col :span="24" class="c-title">
              <!--            <img-->
              <!--              style="width: 50px; height: 50px;"-->
              <!--              src="@/assets/images/logo.png"-->
              <!--              class="c-title-logo"-->
              <!--              alt="logo">-->
              <!--            策地准管理后台-->
            </el-col>
          </el-row>
        </el-header>
        <el-main class="c-login-main">
          <div class="c-login-wrap">
            <!--          登录切换-->
            <el-row class="c-l-ts-wrap">
              <el-col v-if="passwordType === 'password'" :span="6" class="c-l-title">{{ resetPasswordTag ? "找回密码" :
                "密码登录" }}
              </el-col>
              <el-col v-if="!resetPasswordTag" :span="passwordType === 'password' ? 18 : 24" class="c-l-switch">
                <span class="c-l-switch-container">
                  <span class="c-l-switch-tip">{{ passwordType === "password" ? "扫码登录" : "密码登录" }}</span>
                  <svg-icon v-if="passwordType === 'password'" icon-class="erweimadenglu"
                    @click="switchPasswordType('sweepCode')" />
                  <svg-icon v-else icon-class="pc-login" @click="switchPasswordType('password')" />
                </span>
              </el-col>
            </el-row>
            <!--          登录切换-->
            <!--          登录表单-->
            <el-form v-if="passwordType === 'password' && !resetPasswordTag" ref="loginForm" label-width="0"
              :model="loginForm" :rules="loginRules" class="c-login-form">
              <el-row>
                <el-col :span="3" class="login-form-ico">
                  <svg-icon icon-class="login-phone" class="c-login-icon margin-right-default" />
                </el-col>
                <el-col :span="18">
                  <el-form-item prop="loginAccount">
                    <el-input ref="loginAccount" v-model="loginForm.loginAccount" size="default" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row style="margin-top: 10px">
                <el-col :span="3" class="login-form-ico">
                  <svg-icon icon-class="login-password" class="c-login-icon margin-right-default" />
                </el-col>
                <el-col :span="18">
                  <el-form-item prop="loginPassword">
                    <el-input ref="loginPassword" v-model="loginForm.loginPassword" type="password" size="default"
                      @keyup.enter.native="handleLogin" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item>
                <!--  <span style = "float: right; color: #19abff; margin-right: 10px; cursor: pointer" @click = "resetPassword($event, true)">忘记密码？</span> -->
              </el-form-item>
              <div style="text-align: center; margin-top: 30px;">
                <div :class="false === allowLogin || loading ? 'login-button-disabled' : 'login-button'"
                  @click.prevent="handleLogin">{{ loading ? "登录中..." : "登录" }}
                </div>
              </div>
            </el-form>
            <!--          登录表单-->
            <!--          重置密码表单-->
            <el-form v-if="resetPasswordTag" label-width="0" class="c-find-password-form">
              <el-form-item>
                <svg-icon icon-class="login-phone" class="c-login-icon" />
                <el-input style="width: 80%;" />
              </el-form-item>
              <el-form-item>
                <svg-icon icon-class="yanzhengma" class="c-login-icon" />
                <div class="c-q-find-container">
                  <el-input style="width: 70%;" />
                  <span class="c-g-code">获取验证码</span>
                </div>
              </el-form-item>
              <el-form-item>
                <svg-icon icon-class="login-password" class="c-login-icon" />
                <el-input style="width: 80%;" />
              </el-form-item>
              <el-form-item>
                <svg-icon icon-class="login-password" class="c-login-icon" />
                <el-input style="width: 80%;" />
              </el-form-item>
              <div style="text-align: center; margin-top: 30px;">
                <el-button :disabled="true === allowLogin" @click.prevent="handleLogin">确认修改</el-button>
              </div>
              <div style="
                text-align: right;
                margin-top: 20px;
                margin-right: 40px;
                color: #0f99ff;
                font-size: 13px;
              ">
                <span style="cursor: pointer;" @click.prevent="resetPassword($event, false)">返回</span>
              </div>
            </el-form>
            <!--          重置密码表单-->
            <!--          扫码登录表单-->
            <el-form v-if="passwordType !== 'password'" class="c-qrcode-form">
              <el-form-item label="扫码登录">
                <span class="c-qr-title">扫码登录</span>
              </el-form-item>
              <el-form-item label="扫码登录">
                <img class="c-qr-code"
                  src=""
                  alt="扫码">
              </el-form-item>
              <el-form-item label="微信扫码">
                <span class="c-qr-tip">请使用微信扫码登录</span>
              </el-form-item>
            </el-form>
            <!--          扫码登录表单-->
          </div>
        </el-main>
      </el-container>
      <el-footer class="c-login-footer">
        版权所有：@{{ systemName }} <a href="https://beian.miit.gov.cn/" target="_blank" rel="nofollow">{{ putOnRecordNumber
        }}</a>
        <a v-if="true === showBeian2" class="beian2"
          href="https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=35020502000858" target="_blank"
          rel="noreferrer">
          <img src="@/assets/images/gonganbeian.png" class="beian2-icon" alt="闽公网安备">
          闽公网安备35020502000858</a>
      </el-footer>
    </div>
    <div v-if="true === hasNewVersion" class="update-remind-div">
      <div class="update-remind-content-div">
        <div><i class="el-icon-info icon" /></div>
        <div v-if="true === osIsWindows">当前有新版本，请按Ctrl+F5强制刷新</div>
        <div v-if="false === osIsWindows">当前有新版本，请按Command+Shift+R强制刷新</div>
      </div>
    </div>
    <div v-if="true === showRepeatLoginRemind" class="repeat-login-remind-div">
      <div class="repeat-login-remind-content-div">
        <div><i class="el-icon-info icon" /></div>
        <div>当前已有登录账号，如果需要同时登录不同账号，请使用其他浏览器登录</div>
        <div>
          <el-button type="primary" @click="hideRepeatLoginRemind">继续登录（将覆盖已登录的账号）</el-button>
        </div>
      </div>
    </div>
    <version ref="version" />
  </div>
</template>

<script>
import SvgIcon from '@/components/SvgIcon'
import myLocalStorage from '@/utils/localStorage'
import Version from '@/components/version/version.vue'
import { getToken } from '@/utils/auth'

let that

export default {
  name: 'Login',
  components: { SvgIcon, Version },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (undefined === value || value.length === 0) {
        callback(new Error('请填写账号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (undefined === value || value.length === 0) {
        callback(new Error('请填写密码'))
      } else {
        callback()
      }
    }
    return {
      allowLogin: true,
      isSwitchServer: false,
      autoSwitchServer: true,
      versionCode: 0,
      hasNewVersion: false,
      osIsWindows: true,
      systemName: '',
      showRepeatLoginRemind: false,
      putOnRecordNumber: '',
      browserNotSupport: false,
      showBeian2: false,
      loginForm: {
        verifyType: 'account',
        loginAccount: myLocalStorage.getJsonItem('userInfo') == null ? '' : myLocalStorage.getJsonItem('userInfo')['loginAccount'],
        loginPassword: '',
        smsVerify: ''
      },
      loginRules: {
        loginAccount: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        loginPassword: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      resetPasswordTag: false,
      bgImg: require('@/assets/images/login_bg.png')
    }
  },
  watch: {
    $route: {
      handler(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    that = this
    setTimeout(() => {
      this.versionCode = this.$refs.version.versionCode
      this.$api.getVersion({
        appSort: 5,
        version: this.versionCode
      }, undefined).then(res => {
        if (res['versionCode'] > this.versionCode) {
          // this.hasNewVersion = true
          this.allowLogin = true
        } else {
          this.allowLogin = true
        }
      })
    }, 500)
    // 判断是否为谷歌内核
    const tempUserAgent = navigator.userAgent.toLowerCase()
    if (tempUserAgent.indexOf('chrome') === -1 && tempUserAgent.indexOf('safari') === -1) {
      this.browserNotSupport = true
    }
    // window.addEventListener('storage', this.afterQRScan)
    // 判断域名
    const url = location.href
    console.log('href', url)
    let path = url.substring(url.indexOf('//') + 2)
    path = path.substring(path.indexOf('/'))
    if (path.indexOf('/v2/') > -1) {
      this.autoSwitchServer = false
      if (path.indexOf('/v2/2/') > -1) {
        localStorage.setItem('baseURL', this.$api.getMainServiceUrl())
        localStorage.setItem('downloadURL', this.$api.getOriginalDownloadServiceUrl())
      } else {
        if (this.$api.getMainServiceUrl().indexOf('cedizhun.com') > -1) {
          localStorage.setItem('baseURL', 'https://www.cedizhun.com/api/platform')
          localStorage.setItem('downloadURL', 'https://www.xinlingshouxitong.com/download/d?c=')
        } else if (this.$api.getMainServiceUrl().indexOf('192.168.43.221') > -1) {
          localStorage.setItem('baseURL', 'http://192.168.43.221:20000/api/platform')
          localStorage.setItem('downloadURL', 'http://192.168.43.221:20120/d?c=')
        }
      }
    } else {
      localStorage.setItem('baseURL', this.$api.getMainServiceUrl())
      localStorage.setItem('downloadURL', this.$api.getOriginalDownloadServiceUrl())
    }
    if (url.indexOf('xmpfm') > -1) {
      this.systemName = '厦门屏方米信息科技有限公司'
      this.putOnRecordNumber = '闽ICP备2024051184号'
      this.showBeian2 = true
      localStorage.logoSrc = require('@/assets/images/logo_ygl.png')
    } else if (url.indexOf('fjwdc') > -1) {
      this.systemName = '福建五度仓科技有限公司'
      this.putOnRecordNumber = '闽ICP备2023021297号'
      localStorage.logoSrc = require('@/assets/images/logo_wdc.png')
    } else {
      this.systemName = '预策蔚来（厦门）科技有限公司'
      this.putOnRecordNumber = '闽ICP备20005899号-2'
      localStorage.logoSrc = require('@/assets/images/logo.png')
    }
    document.title = this.systemName
    this.osIsWindows = false
    // 判断是否有登录状态
    const sessionToken = getToken()
    // if (undefined !== sessionToken && sessionToken !== '') {
    //   this.showRepeatLoginRemind = true
    // }
  },
  mounted() {
    if (this.loginForm.loginAccount === '') {
      this.$refs.loginAccount.focus()
    } else if (this.loginForm.loginPassword === '') {
      this.$refs.loginPassword.focus()
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    hideRepeatLoginRemind() {
      this.showRepeatLoginRemind = false
    },
    // checkUpdate() {
    //   location.reload(true);
    //   // return;
    //   // let url = 'http://localhost:9528/#/login?redirect=%2Fhomepage';// window.location.href;  //设置请求的地址
    //   // let xmlHttp = new XMLHttpRequest();  //实例化XMLHttpRequest对象
    //   // xmlHttp.open('GET', url, false);  //建立间接，要求异步响应
    //   // xmlHttp.setRequestHeader('If-Modified-Since', '0');
    //   // xmlHttp.setRequestHeader('Cache-Control', 'no-cache, no-store');
    //   // xmlHttp.onreadystatechange = () => {  //绑定响应状态事件监听函数
    //   //   if (4 === xmlHttp.readyState) {  //监听readyState状态
    //   //     if (200 === xmlHttp.status || 0 === xmlHttp.status) {  //监听HTTP状态码
    //   //       console.log(xmlHttp.responseText);  //接收数据
    //   //     }
    //   //   }
    //   // };
    //   // xmlHttp.send('callback=functionName');  //发送请求
    // },
    // checkCapsLock(e) {
    //   const {key} = e;
    //   this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z'
    // },
    // showPwd() {
    //   if (this.passwordType === 'password') {
    //     this.passwordType = ''
    //   } else {
    //     this.passwordType = 'password'
    //   }
    //   this.$nextTick(() => {
    //     this.$refs.password.focus()
    //   })
    // },
    async handleLogin() {
      if (this.allowLogin === false) {
        return
      }
      await this.$refs.loginForm.validate(async valid => {
        if (valid === false) {
          return
        }
        that.loading = true
        this.$api.login(this.loginForm, {
          showLoading: false,
          showDefaultErrorTotal: false
        }).then(res => {
          that.loading = false
          // 店铺登录只有商品管理权限
          if (res['organizationType'] === 5) {
            res.permissionList = [{
              'permissionId': '1',
              'subordinate': false,
              'permissionName': '首页',
              'parentPermissionCode': '',
              'permissionCode': '00',
              'path': '/index.html',
              'permissionType': 1
            }, {
              'permissionId': '14',
              'subordinate': false,
              'permissionName': '商品信息',
              'parentPermissionCode': '01',
              'permissionCode': '0101',
              'path': '',
              'permissionType': 1
            }, {
              'permissionId': '56',
              'subordinate': false,
              'permissionName': '新建商品',
              'parentPermissionCode': '0101',
              'permissionCode': '010101',
              'path': '',
              'permissionType': 0
            }, {
              'permissionId': '3',
              'subordinate': false,
              'permissionName': '基础档案',
              'parentPermissionCode': '',
              'permissionCode': '01',
              'path': '',
              'permissionType': 1
            }, {
              'permissionId': '57',
              'subordinate': false,
              'permissionName': '修改商品',
              'parentPermissionCode': '0101',
              'permissionCode': '010102',
              'path': '',
              'permissionType': 0
            }, {
              'permissionId': '58',
              'subordinate': false,
              'permissionName': '导入商品',
              'parentPermissionCode': '0101',
              'permissionCode': '010103',
              'path': '',
              'permissionType': 0
            }]
          }
          res.loginAccount = this.loginForm.loginAccount
          res.loginTime = new Date().getTime()
          myLocalStorage.setJsonItem('userInfo', res)
          this.$store.dispatch('user/login', res)
          this.$store.dispatch('user/getInfo')
          // 加载自定义支付通道
          that.$api.getOrganizationPayCustomizePayChannelList({
            page: 1,
            pageSize: 999,
            returnCount: false
          }, undefined).then(res => {
            myLocalStorage.setJsonItem('customizePayChannelList', res['list'])
          })
          this.$router.push({
            path: this.redirect || '/homepage',
            query: this.otherQuery
          })
        }, e => {
          that.loading = false
          if (this.autoSwitchServer === false) {
            this.$commonUtils.showErrorToast('登录失败：' + e.message)
            return
          }
          if (this.isSwitchServer === true) {
            this.isSwitchServer = false
            localStorage.setItem('baseURL', this.$api.getMainServiceUrl())
            localStorage.setItem('downloadURL', this.$api.getOriginalDownloadServiceUrl())
            this.$commonUtils.showErrorToast('登录失败：' + e.message)
            return
          }
          // 登录失败尝试切换服务器
          const serverUrl = this.$api.getMainServiceUrl()
          if (serverUrl.indexOf('https://www.cedizhun.com/v2/2') > -1) {
            localStorage.setItem('baseURL', 'https://www.cedizhun.com/api/platform')
            localStorage.setItem('downloadURL', 'https://www.xinlingshouxitong.com/download/d?c=')
            this.isSwitchServer = true
            this.handleLogin()
          } else if (serverUrl.indexOf('http://192.168.43.221:20000/v2/2') > -1) {
            localStorage.setItem('baseURL', 'http://192.168.43.221:20000/api/platform')
            localStorage.setItem('downloadURL', 'http://192.168.43.221:20120/d?c=')
            this.isSwitchServer = true
            this.handleLogin()
          } else {
            this.$commonUtils.showErrorToast('登录失败：' + e.message)
          }
        })
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    switchPasswordType(type) {
      //   this.passwordType = type
    },
    resetPassword(event, tag) {
      this.resetPasswordTag = tag
    }
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  }
}
</script>

<style lang="scss" scoped>
$bg: #f3ece0;
$dark_gray: #889aa4;
$light_gray: #eee;
$baseColor: #f07505;

.login-container {
  width: 100%;
  height: 100%;
  background-size: 100% 100%;
  background-repeat: no-repeat;

  .el-header {
    padding: 0;
  }
}

.c-login-header {
  height: 50px !important;

  .c-lt {
    width: 100%;
    height: 100px;
    /*background: #f9f8f2;*/
    color: $baseColor;

    .c-title-logo {
      height: 100px;
      width: 90%;
    }

    .c-title {
      // line-height: 100px;
      font-weight: bolder;
      font-size: 20px;
      display: flex;
      align-items: center;
      padding: 10px;
    }
  }
}

.c-login-main {
  margin-top: 80px;
  height: calc(100% - 230px);
  display: flex;
  align-items: center;
  justify-content: flex-end;

  .c-login-wrap {
    margin-right: 20px;
    width: 400px;
    height: 450px;
    border: 1px solid #fff;
    border-radius: 10px;
    overflow: hidden;
    background: #fff;
    box-shadow: 0 0 8px $bg;
    padding: 15px;

    .c-l-ts-wrap {
      width: 370px;
      height: 35px;

      .c-l-title {
        font-size: 18px;
        line-height: 35px;
        color: $baseColor;
        font-weight: 700;
        cursor: default;
      }

      .c-l-switch {
        text-align: right;
        font-size: 30px;
        cursor: pointer;

        .c-l-switch-container {
          .c-l-switch-tip {
            display: none;
            padding: 5px 8px;
            font-size: 14px;
            border: 1px solid $baseColor;
            color: $baseColor;
            vertical-align: text-bottom;
            position: relative;
          }

          .c-l-switch-tip:before {
            position: absolute;
            content: "";
            display: block;
            width: 0;
            height: 0;
            border-top: 10px solid transparent;
            border-bottom: 10px solid transparent;
            border-left: 10px solid $baseColor;
            right: -10px;
            top: 3px;
          }

          .c-l-switch-tip:after {
            position: absolute;
            content: "";
            display: block;
            width: 0;
            height: 0;
            border-top: 9px solid transparent;
            border-bottom: 9px solid transparent;
            border-left: 9px solid #fff;
            right: -9px;
            top: 4px;
          }
        }

        .c-l-switch-container:hover {
          .c-l-switch-tip {
            display: inline-block;
          }
        }
      }
    }

    .c-login-form {
      margin-top: 80px;
      text-align: center;

      .login-form-ico {
        height: 36px;
        text-align: right;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }

      .c-login-icon {
        font-size: 22px;
        color: $dark_gray;
        vertical-align: middle;

        .el-input--dedium {
          border-color: $dark_gray !important;
        }
      }
    }

    .c-find-password-form {
      margin-top: 40px;
      text-align: center;

      .c-login-icon {
        font-size: 22px;
        color: $dark_gray;
        vertical-align: middle;
        margin-right: 10px;

        .el-input--dedium {
          border-color: $dark_gray !important;
        }
      }

      .c-q-find-container {
        width: 80%;
        height: 36px;
        display: inline-flex;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        vertical-align: bottom;

        .c-g-code {
          color: $dark_gray;
          cursor: pointer;
        }

        .el-input__inner {
          border: none;
          height: 32px;
          width: 60%;
        }
      }
    }

    .c-qrcode-form {
      margin-top: 40px;
      text-align: center;

      .c-qr-title {
        font-size: 22px;
        font-weight: bolder;
        color: $baseColor;
      }

      .c-qr-code {
        width: 50%;
        height: 50%;
      }

      .c-qr-tip {
        color: $baseColor;
        font-size: 14px;
      }
    }
  }
}

.c-login-footer {
  text-align: center;
  color: #b0b0b0;
  padding-top: 10px;

  span:first-child {
    color: $baseColor;
    font-weight: bolder;
  }
}

.el-button {
  width: 297px;
  margin: 0 auto;
  background: #f07505;
  color: #fff;
  border: 1px $baseColor solid;
}

.login-button {
  cursor: pointer;
  width: 297px;
  height: 40px;
  border-radius: 20px;
  margin: 0 auto;
  background: #f07505;
  color: #fff;
  border: 1px $baseColor solid;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: #e06505;
  }
}

.login-button-disabled {
  cursor: pointer;
  width: 297px;
  height: 40px;
  border-radius: 20px;
  margin: 0 auto;
  background: #eee;
  color: #888;
  border: 1px #e5e5e5 solid;
  display: flex;
  align-items: center;
  justify-content: center;
}

.browser-not-support-remind {
  color: #f07505;
  font-size: 38px;
  line-height: 200%;
  width: 100%;
  text-align: center;
  padding-top: 20px;
}

.browser-not-support-download {
  text-align: center;
  margin-top: 20px;

  a {
    display: inline-block;
    text-align: center;
    border-radius: 25px;
    padding: 3px 20px 0 20px;
    font-size: 20px;
    height: 50px;
    line-height: 40px;
    background: #f07505;
    color: #fff;

    &:hover {
      background: #a06505;
    }
  }
}

.beian2 {
  margin-left: 15px;

  .beian2-icon {
    margin-right: 1px;
    width: 16px;
    height: 17px;
  }
}

.update-remind-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;

  .update-remind-content-div {
    width: 50vw;
    height: 50vh;
    background-color: #fff;
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    font-size: 24px;
    color: var(--color-red);
    line-height: 250%;
    text-align: center;

    .icon {
      font-size: 150px;
      color: #999;
    }
  }
}

.repeat-login-remind-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;

  .repeat-login-remind-content-div {
    width: 50vw;
    height: 50vh;
    background-color: #fff;
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    font-size: 22px;
    color: var(--color-red);
    line-height: 250%;
    text-align: center;

    .icon {
      font-size: 150px;
      color: #999;
    }
  }
}
</style>
